import datetime
import json
import os
from datetime import datetime

from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import render
os.environ
os.environ.setdefault(
    'DJANGO_SETTINGS_MODULE',
    'ihome.settings'
)
# Create your views here.


# 预定订单
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views import View

from homes.models import House
from order.models import Order
from utils.views import login_required


class OrdersAction(View):

    # 预定订单
    @method_decorator(login_required)
    def post(self, request):

        data = json.loads(request.body.decode())

        house_id = data.get('house_id')
        start_date = data.get('start_date')
        end_date = data.get('end_date')

        # 查询房间在当前选择的入住日期还在进行的订单数
        orderd = Order.objects.filter(house_id=house_id,
                                     begin_date__lte=start_date,
                                     end_date__gte=start_date,
                                     status__in=[1,2]).count()

        # 查询当前房间的总个数
        house = House.objects.get(id=house_id)

        # 判断是否有空房
        if orderd >= house.room_count:
            return JsonResponse({'errno': 4004, 'errmsg': '房间已满'})


        user = request.user

        # 构建订单号
        order_id = house_id + timezone.localtime().strftime("%Y%m%d%H%M%S") + "%09d"%user.id

        sd = datetime.strptime(start_date, '%Y-%m-%d')
        ed = datetime.strptime(end_date, '%Y-%m-%d')
        delta = ed - sd
        days = delta.days
        if days == 0 :
            days = 1
        print(days)

        try:
            order = Order.objects.create(
                # id = order_id,
                begin_date = start_date,
                end_date = end_date,
                house_price = house.price,
                status = 0,
                house_id = house_id,
                user_id = user.id,
                days = days,
                amount = house.price * days
            )

            house.order_count += 1

            house.save()

        except Exception as e:
            print(e)
            return JsonResponse({'errno': 4001, 'errmsg': '预定失败'})


        return JsonResponse({'data':{'order_id': 1},
                             'errno': 0,
                             'errmsg': '下单成功'})


    # 订单列表
    @method_decorator(login_required)
    def get(self, request):

        role = request.GET.get('role')

        # 定义订单空列表
        order_list = []

        user = request.user

        if role == 'custom':

            orders = Order.objects.filter(user_id=user.id).order_by('-create_time')

            for order in orders:

                house = House.objects.get(id=order.house_id)
                img_url = settings.QINIU_URL + house.index_image_url
                order_list.append({
                        "amount": order.amount,
                        "comment": order.comment,
                        "ctime": order.create_time,
                        "days": order.days,
                        "end_date": order.end_date,
                        "img_url": img_url,
                        "order_id": order.id,
                        "start_date": order.begin_date,
                        "status": Order.ORDER_STATUS_ENUM[order.status],
                        "title": house.title
                })

            return JsonResponse({'data':{
                                        'orders': order_list},
                                'errno': '0',
                                'errmsg': 'ok'
                                })



        if role == 'landlord':

            # 查询名下所有房屋
            houses = House.objects.filter(user_id=user.id)

            orders = Order.objects.all().order_by('-create_time')

            for order in orders:

                for house in houses:

                    if order.house_id != house.id:
                        continue

                    img_url = settings.QINIU_URL + house.index_image_url

                    order_list.append({
                        "amount": order.amount,
                        "comment": order.comment,
                        "ctime": order.create_time,
                        "days": order.days,
                        "end_date": order.end_date,
                        "img_url": img_url,
                        "order_id": order.id,
                        "start_date": order.begin_date,
                        "status": Order.ORDER_STATUS_ENUM[order.status],
                        "title": house.title
                    })


            # 查询房屋存在的订单
            # for house in houses:
            #
            #     orders = Order.objects.filter(house_id=house.id).order_by('-create_time')
            #
            #     for order in orders:
            #
            #         img_url = settings.QINIU_URL + house.index_image_url
            #
            #         order_list.append({
            #             "amount": order.amount,
            #             "comment": order.comment,
            #             "ctime": order.create_time,
            #             "days": order.days,
            #             "end_date": order.end_date,
            #             "img_url": img_url,
            #             "order_id": order.id,
            #             "start_date": order.begin_date,
            #             "status": Order.ORDER_STATUS_ENUM[order.status],
            #             "title": house.title
            #         })

            return JsonResponse({'data':{
                                        'orders': order_list},
                                'errno': '0',
                                'errmsg': 'ok'
                                })


    # 接单/拒单
    @method_decorator(login_required)
    def put(self, request, order_id):

        # 提取参数
        data = json.loads(request.body.decode())
        action = data.get('action')
        reason = data.get('reason')
        status = None

        if action == 'accept':
            status = 3
        elif action == 'reject':
            status = 6
        else:
            return JsonResponse({'errno': 4103, 'errmsg': '参数错误'})

        try:
            order = Order.objects.get(id=order_id)

            order.status = status
            order.comment = reason
            order.save()

        except Exception as e:
            print(e)
            return JsonResponse({'errno': 4001, 'errmsg': '操作失败'})

        return JsonResponse({'errno': 0,
                             'errmsg': '操作成功',
                             'data':{
                                 'action': action,
                                 'reason': reason
                             }
                             })


# 评论
class Comment(View):

    @method_decorator(login_required)
    def put(self, request, order_id):

        data = json.loads(request.body.decode())

        comment = data.get('comment')

        try:
            order = Order.objects.get(id=order_id).order_by('-create_time')

            order.comment = comment
            order.status = 4
            order.save()

        except Exception as e:
            print(e)
            return JsonResponse({'errno': 4001, 'errmsg': '发表评论失败'})

        return JsonResponse({'errno': 0, 'errmsg': '评论成功'})











